package com.crb.oauth2.api.third;


import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.TreeMap;

/**
 * Package: com.crb.oauth2.api.third
 * Description：
 * Author: huangjian
 * Date:  2020/9/17 16:48
 * Modified By:
 *
 * @author huangjian
 */
@Slf4j
@RestController
@RequestMapping("/notify")
public class NotifyController {

    private static JsonMapper jsonMapper = new JsonMapper();

    private static final String APP_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAyIFeuGtO9TqSOyvPeaIuZLb1n7TWc6Ttj2gFeYk57nElpOTgummSiLE7S1YGaj4BA77vsq2rIgQwikDY+AHvqXBrfHD0KF0dhdpxzcxn60F0E84Q/qvytZzF+rawHp9v21vDQ/xuN9TfYPMwRyQV5PpXPXxc7iRNj91XIsigI38a0kULNil5z8SvteO/fVWDp5vtGC+H4Wu4ktcExUADOLeeVgSL+vd+k0GbCgkz1Q5y1HT2C1fKZF9rkJ/QHvmxATF2MM5Wo61h054qoEyuNBJT7FlT2ctOgrY3qdJgwFxaT3BgVW9WNflT2TeV73+gUHWFhhFwlD8rurUVcRbRYQIDAQAB";

    @PostMapping("/proxy")
    public String proxy(HttpServletRequest request) throws Exception {
        String packageData = handleHttpServletRequest(request);
        log.info("收到原始数据->" + packageData);
        //开始签名验证
        RestfulDTO restfulDTO = jsonMapper.readValue(packageData, RestfulDTO.class);
        TreeMap<String, Object> stringObjectTreeMap = jsonMapper.readValue(jsonMapper.writeValueAsString(restfulDTO.getData()), TreeMap.class);
        log.info("收到业务数据->" + stringObjectTreeMap);
        String sourceSignData = RSASignUtils.getSourceSignData(stringObjectTreeMap);
        log.info(sourceSignData);
        if (RSASignUtils.verifyByPublicKey(sourceSignData.getBytes(), APP_PUBLIC_KEY, restfulDTO.getSign())) {
            log.info("验证签名成功，" + restfulDTO);
            return "sucess";
        }
        log.error("验证签名失败");
        return "fail";
    }


    private String handleHttpServletRequest(HttpServletRequest request) {
        try {
            BufferedReader streamReader = new BufferedReader(new
                    InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            return responseStrBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
